"""
一些公共基类
"""
import logging
import multiprocessing
from threading import Thread
import zmq.asyncio


def _got_dva():
    return multiprocessing.current_process().name


class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]


class DvaSingleton(type):

    def __call__(self, *args, **kwargs):
        pass


class ZmqServer:
    def __init__(self, server_sock_path, name='', logger=None,):
        self._server_sock_path = server_sock_path
        context = zmq.asyncio.Context.instance()
        self._server = context.socket(zmq.ROUTER)
        self._server.bind(self._server_sock_path)

        self._poller = zmq.asyncio.Poller()
        self._poller.register(self._server, zmq.POLLIN)

        self._logger = logger or logging.root
        self.name = name or self.__class__.__name__

    async def run(self) -> None:
        while True:
            msg = None
            try:
                _events = dict(await self._poller.poll())
                msg = await self._server.recv_multipart()

            except Exception as e:
                self._logger.exception(f'zmq server {self.name} handle msg {msg} except: {e}')


class ZmqPubServer:
    pass


class ZmqClient:
    pass


class ZmqSubServer:
    pass
